/*
 * Copyright (c) 2012,腾讯科技有限公司
 * All rights reserved.
 *
 * 文件名称：CommonParser.m
 * 文件标识：
 * 摘 要：
 *
 * 当前版本：1.0
 * 作 者：qitao
 * 完成日期：12-18-2012
 */

#import "CommonParser.h"
#import "ASIDataProvider.h"

@implementation CommonParser

- (id) init
{
    self = [super init];
    if (self != nil) {
        _reqGetDict = [[NSMutableDictionary alloc] init];
        _reqPostDict = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

- (void) dealloc
{
    [_reqGetDict release];
    [_reqPostDict release];
    
    [super dealloc];
}

- (NSDictionary*) userInfo {
    return nil;
}

- (NSString*) requestGroup {
    return @"JsonGroup";
}

- (NSTimeInterval) timeoutDuration {
    return 10;
}

- (NSOperationQueuePriority)priority {
    return NSOperationQueuePriorityNormal;
}


#pragma mark - Download logic

- (void)preprocessRequest:(ASIHTTPRequest*)request
{
    // add post data if needed
    if ([request isKindOfClass:[ASIFormDataRequest class]]) {
        ASIFormDataRequest * postReq = (ASIFormDataRequest*)request;
        if (_reqPostDict.count > 0) {
            [postReq setStringEncoding:CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000)];
            for (id k in _reqPostDict) {
                [postReq setPostValue: [_reqPostDict objectForKey: k] forKey: k];
            }
        }
    }
 
    request.queuePriority = [self priority];
    
    [request setTimeOutSeconds:[self timeoutDuration]];
    
    NSDictionary * userInfo = [self userInfo];
    if (userInfo) [request setUserInfo:userInfo];
}

- (void)noCacheRequestURL:(NSString *)url postData:(NSData*)data completion:(void (^)(NSData *))completion fail:(void (^)(NSError *))fail
{
    if (!NetWorkConnected) {
        if (fail) {
            fail(ERROR_WITH_TYPE_AND_CODE_AND_MESSAGE(-1, -1, @"无法连接服务器，请检查网络连接"));
        }
        return;
    }

    NSString * newUrl = url;
    if (_reqGetDict.count > 0) {
        newUrl = [GToolUtil addQueryStringToUrl:url params:_reqGetDict];
    }

    __block ASIFormDataRequest * request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:newUrl]] autorelease];
    
    if (data) {
        [request appendPostData:data];
    }
    [self preprocessRequest:request];
    
    [request setCompletionBlock:^{
        NSError * err = request.error;
        if (request.responseStatusCode == 200 || request.responseStatusCode == 304) {
            NSData *returnData = [request responseData];
            if (completion) completion(returnData);
        } else {
            if (fail) fail(err);
        }
    }];
    
    [request setFailedBlock:^{
        NSError * err = request.error;
        if (fail) {
            fail(err);
        }
    }];

    [[ASIDataProvider sharedASIDataProvider] addASIRequest:request withGroup:[self requestGroup]];
}

- (void)requestURL:(NSString *)url postData:(NSData*)data completion:(void (^)(NSData *))completion fail:(void (^)(NSError *))fail
{
    if (!NetWorkConnected) {
        if (fail) {
            fail(ERROR_WITH_TYPE_AND_CODE_AND_MESSAGE(-1, -1, @"无法连接服务器，请检查网络连接"));
        }
        return;
    }
    
    NSString * newUrl = url;
    if (_reqGetDict.count > 0) {
        newUrl = [GToolUtil addQueryStringToUrl:url params:_reqGetDict];
    }
    
    __block ASIFormDataRequest * request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:newUrl]] autorelease];
    
    if (data) {
        [request appendPostData:data];
    }
    [self preprocessRequest:request];
    
    [request setCompletionBlock:^{
        NSError * err = request.error;
        if (request.responseStatusCode == 200 || request.responseStatusCode == 304) {
            NSData *returnData = [request responseData];
            if (completion) completion(returnData);
        } else {
            if (fail) fail(err);
        }
    }];
    
    [request setFailedBlock:^{
        NSError * err = request.error;
        if (fail) {
            fail(err);
        }
    }];
    
    [request setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];
    [request setSecondsToCache:60 * 5];
    [request setTimeOutSeconds:10];
    [request setNumberOfTimesToRetryOnTimeout:1];
    
    [[ASIDataProvider sharedASIDataProvider] addASIRequest:request withGroup:[self requestGroup]];
}


@end
